package handler;

import service.CourseService;
import service.StudentService;
import service.impl.CourseServiceImpI;
import service.impl.StudentServiceImpI;
import view.*;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CourseViewHandler implements ActionListener {
    private CourseView courseView;

    public CourseViewHandler(CourseView courseView) {
        this.courseView = courseView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("增加".equals(text)) {
            new AddCourseView(courseView);

        } else if ("修改".equals(text)) {
            //new UpdateCoursView(courseView,);
            int[] selectCourseIds = courseView.getSelectCourseIds();
            if (selectCourseIds.length != 1) {
                JOptionPane.showMessageDialog(courseView, "一次只能修改一个");
                return;
            }
            new UpdateCoursView(courseView, selectCourseIds[0]);
        } else if ("删除".equals(text)) {
            int[] selectStudentIds = courseView.getSelectCourseIds();
            if (selectStudentIds.length == 0) {
                JOptionPane.showMessageDialog(courseView, "请选择要删除的行");
                return;
            }
            int option = JOptionPane.showConfirmDialog(courseView, "确认删除所选择的" + selectStudentIds.length + "行吗？", "确认删除", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {//确认
                //执行删除
                CourseService courseService = new CourseServiceImpI();
                boolean deleteResult = courseService.delete(selectStudentIds);
                if (deleteResult) {
                    //重新加载表格
                    courseView.reloadTable();
                    //updateStudentView.dispose();
                } else {
                    JOptionPane.showMessageDialog(courseView, "删除失败");
                }
            }
        } else if ("查询".equals(text)) {
            courseView.setPageNow(1);
            courseView.reloadTable();
        } else if ("上一页".equals(text)) {
            courseView.setPageNow(courseView.getPageNow() - 1);
            courseView.reloadTable();
        } else if ("下一页".equals(text)) {
            courseView.setPageNow(courseView.getPageNow() + 1);
            courseView.reloadTable();
        }
    }
}
